import {
  post,
  get,
  tcptApi,
  ht_api,
  ak
} from './utils/api'
import {
  posts,
  uploads,
  gets,
  deletes
} from './utils/apis'
import {
  baidu_map
} from "./utils/tx_map"
import TIM from './static/tim-wx-friendship.js'
import {
  setTitle,
  caculateTimeago,
  is_auth
} from './utils/util'
import TIMUploadPlugin from './static/tim-upload-plugin'
import logger from './utils/logger'
import {
  SDKAPPID
} from './debug/GenerateTestUserSig'
import {
  innerAudioContext
} from "./utils/wechatSI"


App({
  onLaunch() {
    wx.removeStorageSync('share_partner_name')
    wx.removeStorageSync('my_partner_name')
    const envVersion = wx.getAccountInfoSync().miniProgram.envVersion;
    this.globalData.envVersion = envVersion

    if (ak) {
      this.globalData.ak = ak
    }

    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      console.log(res.hasUpdate)
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })



    gets('/api/upload/info').then(res => {
      wx.setStorageSync('qiniu_upload_token', res.data.data.token)
      wx.setStorageSync('qiniu_upload_domain', res.data.data.domain)
    })


    // wx.removeStorageSync('city');
    wx.getSystemInfo({
      success: (res) => {
        let modelmes = res.model;
        let platform = res.platform;
        if (platform == 'ios') {
          this.globalData.isIos = true;
        }
        if (modelmes.search(/iPhone X/) != -1 || modelmes.search(/iPhone 11/) != -1 || modelmes.search(/iPhone 12/) != -1 || modelmes.search(/iPhone 13/) != -1 || modelmes.search(/iPhone 14/) != -1 || modelmes.search(/iPhone 15/) != -1 || modelmes.search(/iPhone15/) != -1) {
          this.globalData.isIphoneX = true;
        }
        let iosSABottom = Number(res.screenHeight - res.safeArea.bottom);
        this.globalData.Tabheight = iosSABottom;
        let totalTopHeight = (wx.getMenuButtonBoundingClientRect().bottom + wx.getMenuButtonBoundingClientRect().top) - (res.statusBarHeight * 2)
        let titleBarUsableWidth = wx.getMenuButtonBoundingClientRect().left;
        this.globalData.statusBarHeight = res.statusBarHeight;
        this.globalData.titleBarHeight = totalTopHeight;
        this.globalData.titleBarUsableWidth = titleBarUsableWidth;
        this.globalData.barUsableHeight = wx.getMenuButtonBoundingClientRect().height;
        this.globalData.barUsableTop = wx.getMenuButtonBoundingClientRect().top;
        this.globalData.barUsableBottom = wx.getMenuButtonBoundingClientRect().bottom;
        this.globalData.windowHeight = res.screenHeight;
        this.globalData.screenHeight = res.windowHeight;
        this.globalData.windowWidth = res.windowWidth;
        this.globalData.version=res.version
      },
      fail: () => {
        this.globalData.statusBarHeight = 20
        this.globalData.titleBarHeight = 44
      }
    })

    wx.setStorageSync('islogin', false)
    const SDKAppID = this.globalData.SDKAppID
    wx.setStorageSync(`TIM_${SDKAppID}_isTUIKit`, true)
    wx.$TUIKit = TIM.create({
      SDKAppID: this.globalData.SDKAppID
    })
    wx.$TUIKit.registerPlugin({
      'tim-upload-plugin': TIMUploadPlugin
    })
    
    wx.$TUIKitTIM = TIM
    wx.$TUIKitEvent = TIM.EVENT
    wx.$TUIKitVersion = TIM.VERSION
    wx.$TUIKitTypes = TIM.TYPES
    // 监听系统级事件
    wx.$TUIKit.on(wx.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady)
    wx.$TUIKit.on(wx.$TUIKitEvent.KICKED_OUT, this.onKickedOut)
    wx.$TUIKit.on(wx.$TUIKitEvent.ERROR, this.onTIMError)
    wx.$TUIKit.on(wx.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange)
    wx.$TUIKit.on(wx.$TUIKitEvent.SDK_RELOAD, this.onSDKReload)
    wx.$TUIKit.on(wx.$TUIKitEvent.SDK_READY, this.onSDKReady)
    wx.$TUIKit.on(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);

    wx.setEnable1v1Chat({
      enable: true
    })

  },

  handleTcp() {
    const accountInfo = wx.getAccountInfoSync();
    const appId = accountInfo.miniProgram.appId;
    if (appId != 'wxc59b1161a69bc74a') {
      // return
    }
    let uid = ""
    if (wx.getStorageSync("userInfo")) {
      uid = wx.getStorageSync("userInfo").id
    } else {
      uid = 0
    }
    innerAudioContext.init()
    let tcp = wx.createTCPSocket()
    tcp.connect({
      address: tcptApi,
      port: 8282
    })
    tcp.onConnect(() => {
      console.log("onConnect")
      tcp.write('{"operation":"login","uid":' + uid + '}')
      setInterval(() => {
        tcp.write('{"operation":"pong","uid":' + uid + '}')
      }, 30000)
    })
    tcp.onMessage((message) => {
      console.log("onMessage")
      this.getUint8Value(message.message, (e) => {
        console.log(e)
        let val = JSON.parse(e)
        console.log(val)
        if (val.operation == "error") {
          this.handleTcp()
        } else if (val.operation == "voice") {
          innerAudioContext.readText(val.message)
        } else if (val.operation == "cfcancel") {
          if (this.globalData.coffee_order_no == val.order_number) {
            wx.reLaunch({
              url: '/pages/product/soe?type=cfcancel',
            })
          }
        } else if (val.operation == "cfpay") {
          if (this.globalData.coffee_order_no == val.order_number) {
            wx.reLaunch({
              url: '/pages/product/soe?type=cfpay&pay_number=' + val.price,
            })
          }
        }
      })
    })
    tcp.onError((res) => {
      console.log(res)
    })
  },

  getUint8Value(e, t) {
    for (var a = e, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) n += String.fromCharCode(i.getUint8(s));
    t(n);
  },
  str2ab(str) {
    var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    var bufView = new Uint16Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  },

  showToast(title) {
    wx.showToast({
      title,
      icon: 'none'
    })
  },

  showModal(content, showCancel = false, confirmText = "确定", cancelText = "取消", title = "提示") {
    return new Promise((reslove, reject) => {
      wx.showModal({
        title,
        content,
        confirmText,
        cancelText,
        showCancel,
        success: (res) => {
          if (res.confirm) {
            reslove()
          } else if (res.cancel) {
            reject()
          }
        }
      })
    })
  },

  to_back(url = "") {
    if (getCurrentPages().length == 1) {
      if (url) {
        wx.reLaunch({
          url
        })
      } else {
        wx.reLaunch({
          url: '/pages/index/blank',
        })
      }
    } else {
      wx.navigateBack()
    }
  },

  phoneCall(phonenob) {
    posts('/api/ouyoung/third/sorting/ouyapi/numberofprivacy', {
      phonenoa: wx.getStorageSync('userInfo').phonenumber,
      phonenob
    }).then(res => {
      if (res.data.code != 1) {
        this.showModal(res.data.msg)
        return
      }
      let phoneNumber = res.data.data.call
      wx.makePhoneCall({
        phoneNumber
      })
    })
  },

  blockchain() {
    posts('/api/app/wallet/sorting/ouyapi/blockchain.html').then(res => {

    })
  },

  ishouse(obj, type = 1) {
    // 判断是否为家政员
    // 1 = im; 2 = uid; 3 = hid;  
    return new Promise((reslove, reject) => {
      posts('/index.php/api/app/user/sorting/ouyoung_api/ishouse', {
        type,
        ...obj
      }).then(res => {
        if (res.data.code == 1) {
          reslove(res.data)
        }
      })
    })
  },


  copy(data) {
    return new Promise((a, b) => {
      wx.setClipboardData({
        data,
        success: () => {
          a()
        }
      })
    })
  },


  reverse_geocoding(latitude, longitude) {
   
    return new Promise((reslove, reject) => {
      baidu_map(latitude, longitude).then(result => {
         console.log("调用成功了？？？");
        reslove(result)
      })
    })
  },

  i_bx(id) {
    return new Promise((reslove, reject) => {
      posts('/api/app/wallet/sorting/ouyapi/oy_bx', {
        id
      }).then((res) => {
        if (res.data.code == 1) {
          let pay_info = res.data.data
          wx.requestPayment({
            ...pay_info,
            success: (e) => {
              reslove()
            },
          })
        } else {
          this.showModal(res.data.msg)
        }
      })
    })
  },



  getEvaluatedNum() {
    // 获取用户待评价数量
    return new Promise((reslove, reject) => {
      posts('/api/ouyoung/work/getEvaluatedNum?uid=' + wx.getStorageSync('userInfo').id).then((res) => {
        reslove(res.data)
      })
    })
  },

  getTcEvaluatedNum() {
    // 获取套餐订单用户待评价数量
    return new Promise((reslove, reject) => {
      posts('/api/ouyoung/work/getTcEvaluatedNum?uid=' + wx.getStorageSync('userInfo').id).then((res) => {
        reslove(res.data)
      })
    })
  },

  sendMsgToFw(im) {
    // im = 接收人的
    // 用户发送信息服务通知接口
    return new Promise((reslove, reject) => {
      posts('/api/ouyoung/socket/sendMsgToFw?im=' + im).then((res) => {
        reslove(res.data)
      })
    })
  },

  openmap(latitude, longitude) {
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      scale: 18
    })
  },


  contact(service_type = "") {
    posts('/api/app/user/sorting/ouyoung_api/kftype', {
      service_type
    }).then(res => {
      let list = [];
      let itemList = [];
      if (res.data.code == 1) {
        list = res.data.data;
        list.forEach((v, i) => {
          itemList.push(v.name)
        })
      }
      // itemList.push("退款申请")
      wx.showActionSheet({
        itemList,
        success: (r) => {
          // if (r.tapIndex == (itemList.length - 1)) {
          //   wx.navigateTo({
          //     url: '/pages/my/fk?problem_curr=7',
          //   })
          // } else {
            let type = list[r.tapIndex].type
            this.get_service_url(type)
          // }
        },
      })
    })
  },

  join1v1Chat(nickname, openid, roomType = 1) {
    wx.join1v1Chat({
      caller: {
        nickname: wx.getStorageSync('userInfo').name,
        openid: wx.getStorageSync('userInfo').openid
      },
      listener: {
        nickname,
        openid
      },
      roomType: roomType == 1 ? 'voice' : 'video',
      success: (res) => {
        console.log(res)
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  get_service_url(service_type) {
    post({
      url: '/api/index/service_distribution?service_type=' + service_type
    }, true).then(r => {
      if (r.data.code == 1) {
        wx.openCustomerServiceChat({
          extInfo: {
            url: r.data.data.service_url
          },
          corpId: 'ww425c9877e88b4df4'
        })
      } else {
        this.showModal(r.data.msg)
      }
    })
  },

  is_auth(is_pay = false) {
    return is_auth(is_pay)
  },

  previewImage(urls, current = "") {
    wx.previewImage({
      urls,
      current
    })
  },

  resetLoginData() {
    let promise = wx.$TUIKit.logout();
    promise.then((imResponse) => {
      console.log('登出成功---------------------------------------')
      wx.removeStorageSync('userInfo')
    }).catch(function (imError) {
      console.warn('logout error:', imError);
    });
    this.globalData.expiresIn = ''
    this.globalData.sessionID = ''
    this.globalData.userInfo = {
      userID: '',
      userSig: '',
      token: '',
      phone: '',
    }
    this.globalData.userProfile = null
    logger.log(`| app |  resetLoginData | globalData: ${this.globalData}`)
  },

  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })
  },

  applettab() {
    post({
      url: '/api/ouyoung/applettab',
    }, true).then(res => {
      if (res.data.code == 1) {
        this.globalData.applettab_info = res.data.data
      }
    })
  },

  appletpayves() {
    post({
      url: '/api/ouyoung/appletpayves'
    }, true).then(res => {
      if (res.data.code == 1) {
        this.globalData.appletpayves_info = res.data.data
      }
    })
  },

  get_switch() {
    post({
      url: '/api/applet.ouyoung/switch.html'
    }, true).then(res => {
      if (res.data.code == 1) {
        this.globalData.switch_info = res.data.data
      }
    })
  },

  payPlugin(orderNo) {
    return new Promise((a, b) => {
      wx.navigateTo({
        url: 'plugin://payPlugin/pay?orderNo=' + orderNo,
        events: {
          getPayStatus: (data) => {
            console.log(data)
            console.log('--------------------------------------------------')
            let status = data.status
            // 0:支付成功 1:用户取消支付
            if (status == 0) {
              a()
            } else {
              b()
            }
          }
        }
      })
    })
  },

  globalData: {
    isIphoneX: false,
    isIos: false,
    // userInfo: userID userSig token phone
    isTUIKit: true,
    // 个人信息
    userProfile: null,
    headerHeight: 0,
    version:'',
    SDKAppID: SDKAPPID,

    conversationList: [],
    unreadCount: 0, //未读消息数

    userInfo: null,
    statusBarHeight: 0,
    titleBarHeight: 0,
    titleBarUsableWidth: 0,
    barUsableHeight: 0,
    barUsableTop: 0,
    barUsableBottom: 0,
    windowHeight: 0,
    windowWidth: 0,
    Tabheight: 0,
    post,
    get,
    posts,
    ht_api,
    gets,
    uploads,
    deletes,
    setTitle,
    tabBar: [],
    is_show: false, //审核状态
    pop_num: 0, //首页弹窗次数
    pop_merchant_num: 0,//家政端弹窗次数
    pop_aunt_num: 0,//家政员端弹窗次数
    show_ad_num: 0, //是否已播放激励广告
    id_judge: false, //是否已判断用户身份
    coffee_order_no: '',
    ak: '1Hm9KimqpgGIwGlxIfGmG22DgrnmKZL7',
    apptype: 14, //3超有幸福家政 6幸福赢行 为爱护航 2中数社区 1家园 50一刻钟 12幸福一刻钟 14小福星家政
    envVersion: 'release',
    applettab_info: {
      // 1 显示 2隐藏
      shop: 1, // 商城
      study: 1, // 商学院
      hy: 1, // 会员卡
      qrcode: 1, // 二维码
      yuanka: 1, //跳转缘咖
    },
    appletpayves_info: {
      hy: 1, //1 旧支付 2 连连支付 3扫码富
      work: 1, // 1 家政员旧支付
      par: 1,
    },
    switch_info: {
      certified: true,
      course: true
    },
  },
  updwxinfo(data) {
    return new Promise((a, b) => {
      getApp().globalData.post({
        url: '/api/applet.login/updwxinfo.html',
        data
      }, true).then(r => {
        let data = r.data.data
        wx.setStorageSync("userInfo", data);
        a()
      })
    })
  },
  onSDKReady() {
    let updateMyProfile = wx.$TUIKit.updateMyProfile({
      profileCustomField: [{
        key: 'Tag_Profile_Custom_phone',
        value: wx.getStorageSync('userInfo').phonenumber
      }]
    });
    updateMyProfile.then(function (Profile_res) {
      console.log(Profile_res.data); // 更新资料成功
    }).catch(function (Profile_err) {
      console.warn('updateMyProfile error:', Profile_err); // 更新资料失败的相关信息
    });
  },
  onSdkNotReady() {

  },
  onKickedOut() {
    wx.showToast({
      title: '您被踢下线',
      icon: 'error',
    })
  },
  onUpdateGroupProfile(groupID, options = {}) {
    return new Promise((reslove, reject) => {
      let promise = wx.$TUIKit.updateGroupProfile({
        groupID,
        ...options
      });
      promise.then(function (imResponse) {
        reslove()
        console.log(imResponse.data.group) // 修改成功后的群组详细资料
      }).catch(function (imError) {
        reject()
        console.warn('updateGroupProfile error:', imError); // 修改群组资料失败的相关信息
      });
    })
  },
  onTIMError() {

  },
  onNetStateChange() {

  },
  onSDKReload() {

  },
  //tim打开
  onConversationListUpdated() {
    return
    console.log("tim有运行？？？？？");
    let promise = wx.$TUIKit.getConversationList();
    console.log(2333);
    promise.then((imResponse) => {
      let conversationList = imResponse.data.conversationList;
      conversationList.forEach((v, i) => {
        v.lastMessage.lastTimeVal = caculateTimeago(v.lastMessage.lastTime * 1000)
      })
      this.globalData.conversationList = conversationList
      let unreadCount = 0;
      if (conversationList.length > 0) {
        conversationList.forEach((v, i) => {
          unreadCount = unreadCount + v.unreadCount
        });
      }
      if (unreadCount > 99) {
        unreadCount = "99+"
      }
      this.globalData.unreadCount = unreadCount;
    })
  },
})